<?php

namespace Admin\Controller;

class CouponController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("Coupon");
    }

    //首页
    public function index() {

        $requestMap = $this->convertRequestToMap();
        if($requestMap["o#status"] == -2){
            unset($requestMap["o#status"]);
//            $requestMap["o#status-neq"] = array(1,2);
            $requestMap["cp#used"] = 0;
        }
        if(!isNullOrEmpty($requestMap["o#pay_time-elt"])){
            $requestMap["o#pay_time-elt"] .= " 23:59:59";
        }
        unset($requestMap["pageSize"]);
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
//        $requestMap["fo.enterprise_code"] = $user["enterprise_code"];
        $this->assign("begin_time", $_REQUEST["o#pay_time-egt"]);
        $this->assign("end_time", $_REQUEST["o#pay_time-elt"]);

        //分页
        $count = $this->currentModel->getListCount($requestMap);
        $pageSize = $_REQUEST["pageSize"];
        if(isNullOrEmpty($pageSize)){
            $pageSize = 20;
            $page = $this->page($count, $pageSize);
        }else{
            if($pageSize == -1){
                $page = $this->page($count, 0);
            }else{
                $page = $this->page($count, $pageSize);
            }
        }
        $this->assign('pageSize', $pageSize);

        $orderList = $this->currentModel->queryForList($page, $requestMap);

        $totalCount = sizeof($orderList);
        $totalNumber = 0;
        $totalPrice = 0;
        foreach ( $orderList as $item) {
            $totalNumber += $item["number"];
            $totalPrice += ($item["price"] * $item["number"]);
        }

        $this->assign('totalCount', $totalCount);
        $this->assign('totalNumber', $totalNumber);
        $this->assign('totalPrice', $totalPrice);

        $this->assign("user", $user);
        $this->assign("defaultEnum", C("INVOICE_TYPE"));
        $this->assign("statusEnum", C("COUPON_ORDER_STATUS"));
        $this->assign('orderList', $orderList);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->display();

    }

    public function getTable()
    {
//        $data = self::getData();
        $ids = $_REQUEST["id"];
        $type = $_REQUEST["type"];
        if($type == "qrcode"){
            $map['class_name'] = "qrcode_coupon";
        }
        if($type == "reporting"){
            $map['class_name'] = "reporting_coupon";
        }

        $formDict = D("FormDict")->queryForList($map);

        $data = array();
        $data["header"] = array();
        $data["volume"] = array();
        $data["list"] = array();
        foreach ($formDict as $key => $value){
            array_push($data["header"], $value);
            array_push($data["volume"], $key);
        }

//        $users_obj= M("admin");
//        $userId=$_SESSION['ADMIN_ID'];
//        $user=$users_obj->where("user_id=$userId")->find();

        //获取列表
        $list = D("Coupon")->alias("cp")
            ->join("left join __PRODUCT__ p on p.product_id = cp.product_id")
            ->join("left join __ORDER__ o on o.order_id = cp.order_id")
            ->join("left join __CUSTOMER__ cus on cus.customer_id = o.customer_id")
            ->order("cp.coupon_id asc")
            ->field("cp.*, p.product_name, p.image_url, cus.nickname, o.status, o.patient_name, o.doctor_name, o.hospital_name, o.pay_time, o.need_invoice, o.invoice_name, o.invoice_number, o.receive_name, o.receive_contact, o.receive_address,o.express_company, o.delivery_number, o.outstock_time, o.note")
            ->select();

//        $ids = $_REQUEST["id"];
        $idArr = explode(',', $ids);
        $numberSum = 0;
        $totalPriceSum = 0;
        $sumName = "product_name";
        $numberName = "number";
        $priceName = "price";
        foreach ($list as $item){
            if(in_array($item["coupon_id"], $idArr)){
                $item["size"] = "[" . $item["size"] . "]";
                array_push($data["list"], $item);
                $numberSum += $item[$numberName];
                $totalPriceSum += $item[$priceName];
            }
        }

        $newItem = $list[0];
        foreach ($newItem as $key=>$value){
            if($key == $numberName)
                $newItem[$key] = $numberSum;
            elseif($key == $priceName)
                $newItem[$key] = $totalPriceSum;
            else
                $newItem[$key] = "";
        }
        $newItem[$sumName] = "合计";
        array_push($data["list"], $newItem);

        $data["bold"] = (string)(sizeof($idArr)+2);
//        $data["red"] = (string)(sizeof($idArr)+2);

//        $fileName = "定制产品报表_".date('Ymd',time());
        if($type == "qrcode"){
            $fileName = "60_40二维码";
        }
        if($type == "reporting"){
            $fileName = "CP订单报表_" . date('Ymd',time());
        }

        exportExcel($data, $fileName);
    }

    public function remove() {

        $id = $_REQUEST['id'];
        $this->currentModel->deleteById($id);

        $this->success('删除成功!', U("Coupon/index"));

    }

    public function add() {
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $listProduct = D('Product')->alias("p")
            ->join("left join __SUPPLIER__ sp on sp.supplier_id = p.supplier_id")
//            ->where(array('enterprise_code'=>$user["enterprise_code"]))
            ->order("product_id asc")
            ->field("p.*,sp.supplier_name")
            ->select();

        $this->assign("user", $user);
        $this->assign("listProduct", $listProduct);
        $this->display("add");
    }

    public function addPost() {
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $data["update_id"] = $user["employee_id"];
        $data["create_time"] = getCurrentDate();
        $data["product_id"] = $_REQUEST["product_id"];
        $data["price"] = $_REQUEST["price"];
        $data["coupon_hospital_id"] = $_REQUEST["coupon_hospital_id"];
        $data["size"] = $_REQUEST["size"];
        $data["number"] = $_REQUEST["number"];
        $data["default_doctor_name"] = $_REQUEST["default_doctor_name"];
        $data["default_hospital_name"] = $_REQUEST["default_hospital_name"];

        $randomCode = randomCode(6);
        $couponHospital = D("CouponHospital")->where(array('coupon_hospital_id'=>$data["coupon_hospital_id"]))->find();
        $data["coupon_code"] = $couponHospital["coupon_hospital_code"] . $data["size"] . $randomCode;
        $data["qrcode_url"] = "http://".C('WEB_HOST')."/wechat/order/couponOrder?couponCode=" . $data["coupon_code"];
        $data["used"] = 0;
        $id = D("Coupon")->add($data);
        $data["code"] = 200;
        $data["id"] = $id;
        if(isNullOrEmpty($id)){
            $data["code"] = -1;
            $data["msg"] = "添加失败";
        }
        echo json_encode($data);
    }
}